<template>
  <div class="resource-apply">
    <Crumbs :title="orderNo !== undefined ? '资源申请流转' : '资源申请新增'" />
    <div class="main">
      <div class="title-info">工单详情</div>
      <el-row>
        <el-form
          :inline="true"
          :model="formData"
          size="small"
          ref="formref"
          :rules="formrules"
        >
          <el-form-item label="工单类型" prop="orderType">
            <el-select
              v-model="formData.orderType"
              placeholder="工单类型"
              clearable
              :disabled="operationFlat == true ? false : true"
            >
              <el-option label="IaaS资源申请" value="5"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="工单描述" prop="orderDesc">
            <el-input
              v-model="formData.orderDesc"
              placeholder=""
              :disabled="operationFlat == true ? false : true"
            ></el-input>
          </el-form-item>
          <el-form-item label="优先级" prop="priority">
            <el-select
              v-model="formData.priority"
              placeholder="优先级"
              clearable
              :disabled="operationFlat == true ? false : true"
            >
              <el-option label="紧急" value="0"></el-option>
              <el-option label="高" value="1"></el-option>
              <el-option label="中" value="2"></el-option>
              <el-option label="低" value="3"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="截止日期" prop="endDate">
            <el-date-picker
              v-model="formData.endDate"
              type="date"
              :picker-options="expireTimeOption"
              value-format="yyyy-MM-dd"
              clearable
              :disabled="operationFlat == true ? false : true"
            />
          </el-form-item>
        </el-form>
      </el-row>
      <div class="title-info">申请资源列表</div>
      <el-row v-if="operationFlat">
        <el-button size="small" type="primary" @click="iaasApplyBtn"
          >申请资源</el-button
        >
        <el-button size="small" type="primary" @click="deleteon"
          >批量删除</el-button
        >
        <el-button
          size="small"
          type="primary"
          @click="tableEditable = true"
          :disabled="tableEditable"
          >编辑</el-button
        >
        <el-button size="small" type="primary" @click="saveTable"
          >保存</el-button
        >
      </el-row>
      <br />
      <el-row>
        <el-table :data="tableData" ref="tableref" style="width: 100%">
          <el-table-column type="selection" />
          <el-table-column label="资源名称" fixed min-width="200">
            <template slot-scope="scope">
              <template v-if="tableEditable">
                {{ scope.row.resourceName }}
              </template>
              <template v-else>
                {{ scope.row.resourceName }}
              </template>
            </template>
          </el-table-column>
          <el-table-column label="资源使用期限" min-width="230" fixed>
            <template slot-scope="scope">
              <template v-if="tableEditable">
                <el-date-picker
                  v-model="scope.row.serviceLife"
                  type="date"
                  :picker-options="expireTimeOption"
                  value-format="yyyy-MM-dd"
                  :clearable="false"
                  placeholder="选择时间"
                  :disabled="operationFlat == true ? false : true"
                />
              </template>
              <template v-else>
                {{ scope.row.serviceLife }}
              </template>
            </template>
          </el-table-column>
          <el-table-column label="备注" width="200" fixed>
            <template slot-scope="scope">
              <template v-if="tableEditable">
                <el-input v-model="scope.row.remark" style="width: 100%" />
              </template>
              <template v-else>
                {{ scope.row.remark }}
              </template>
            </template>
          </el-table-column>
          <el-table-column
            :label="`${item.paramName}${item.unit ? `(${item.unit})` : ''}`"
            v-for="item in labels"
            :key="item.paramId"
            min-width="200"
          >
            <template slot-scope="scope">
              <template v-if="tableEditable">
                <el-select
                  v-model="scope.row.applyValue[item.applyKey].text"
                  @blur="selectBlur"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item2 in item.enumValue"
                    :key="item2"
                    :label="item2"
                    :value="item2"
                  >
                  </el-option>
                </el-select>
              </template>
              <template v-else>
                {{ scope.row.applyValue[item.applyKey]['text'] }}
              </template>
            </template>
          </el-table-column>
          <el-table-column label="操作" v-if="operationFlat" fixed="right">
            <template slot-scope="scope">
              <el-button
                size="small"
                type="text"
                @click="deleteone(scope.$index)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-row>
      <div v-if="orderNoflat">
        <div class="title-info">工单流转轨迹</div>
        <el-row>
          <el-table
            :data="tableData2"
            stripe
            :header-cell-style="{ backgroundColor: '#FAFAFA' }"
          >
            <el-table-column prop="createBy" label="处理人" />
            <el-table-column prop="createdTime" label="处理时间" />
            <el-table-column prop="operType" label="操作">
              <template slot-scope="scope">
                <span v-if="scope.row.operType === '1'">回复</span>
                <span v-if="scope.row.operType === '2'">转派</span>
                <span v-if="scope.row.operType === '3'">关闭</span>
              </template>
            </el-table-column>
            <el-table-column prop="operOpinions" label="操作意见" />
          </el-table>
        </el-row>
        <div v-if="roamflat == '2'">
          <div class="title-info">工单操作</div>
          <el-form
            :model="roamformInline"
            label-width="80px"
            :rules="roamrules"
            ref="roamdialog"
          >
            <el-row type="flex">
              <el-col :span="8">
                <el-form-item label="操作类型" prop="operType">
                  <el-select
                    v-model="roamformInline.operType"
                    style="width: 350px"
                    placeholder=""
                    @change="opachange"
                    clearable
                  >
                    <el-option label="回复" value="1"></el-option>
                    <el-option
                      label="转派"
                      value="2"
                      v-if="deleteflat == false"
                    ></el-option>
                    <el-option label="关闭" value="3"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="转派角色" prop="character">
                  <el-select
                    v-model="roamformInline.character"
                    style="width: 350px"
                    placeholder=""
                    clearable
                    :disabled="reassignment"
                    @change="characterchange"
                  >
                    <el-option
                      v-for="item in characteroptions"
                      :key="item.roleId"
                      :label="item.roleName"
                      :value="item.roleId"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="转派用户" prop="roleId">
                  <el-select
                    v-model="roamformInline.roleId"
                    style="width: 350px"
                    placeholder=""
                    clearable
                    :disabled="reassignment"
                  >
                    <el-option
                      v-for="item in roleIdoptions"
                      :key="item.optionValue"
                      :label="item.optionText"
                      :value="item.optionValue"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <br />
            <el-row type="flex">
              <el-col :span="24">
                <el-form-item label="操作意见" prop="operOpinions">
                  <el-input
                    type="textarea"
                    style="width: 1000px"
                    v-model="roamformInline.operOpinions"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
        <br />
      </div>
      <br />
      <el-row type="flex" justify="center">
        <el-button
          size="small"
          @click="$router.push('/resApplyWorkOrderManagement')"
          >取 消</el-button
        >
        <el-button size="small" type="primary" @click="submit">确定</el-button>
      </el-row>
    </div>
    <!-- 资源申请的dialog -->
    <el-dialog
      title="申请资源"
      :visible.sync="iaasApplyDialog"
      width="80%"
      v-if="iaasApplyDialog"
    >
      <div>
        <IaasDialog ref="IaasDialog" :tickTableData="tableData" />
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="iaasApplyDialog = false">取 消</el-button>
        <el-button type="primary" @click="iassApplyDialogSub">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 确定时间的选择 -->
    <el-dialog
      title="申请资源"
      :visible.sync="timeDialogVisible"
      width="50%"
      v-if="timeDialogVisible"
    >
      <div>
        <el-form
          :model="timeForm"
          :rules="timerules"
          ref="timeRef"
          label-width="120px"
          class="demo-ruleForm"
        >
          <el-form-item label="资源使用期限" prop="serviceLife">
            <el-date-picker
              v-model="timeForm.serviceLife"
              :picker-options="expireTimeOption"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="选择日期"
            >
            </el-date-picker>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="timeDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="timeDialogSub">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import IaasDialog from './IaasApplyDialog.vue'
export default {
  components: { IaasDialog },
  data () {
    return {
      tableDataCopy: [],
      timerules: {
        "serviceLife": [
          { required: true, message: '请选择资源使用期限', trigger: 'blur' },
        ],
      },
      timeForm: {
        serviceLife: '',
      },
      timeDialogVisible: false,
      ids: undefined,
      applyValue: {},
      labels: [],
      iaasApplyDialog: false,
      deleteflat: true,
      //设置失效日期今天之前的日期不可选
      expireTimeOption: {
        disabledDate (date) {
          //disabledDate 文档上：设置禁用状态，参数为当前日期，要求返回 Boolean
          return date.getTime() < Date.now() - 24 * 60 * 60 * 1000;
        },
      },
      // 工单详情控制
      // 工单状态
      roamflat: '',
      // 工单编号
      orderNo: '',
      // 判断新增还是流转
      orderNoflat: false,
      tableEditable: false,//表格是否处于编辑状态
      formrules: {
        orderType: [
          { required: true, message: '请选择工单类型', trigger: 'change' },
        ],
        orderDesc: [
          { required: true, message: '请输入工单描述', trigger: 'change' },
          {  max: 200, message: '长度在200个字符内', trigger: 'change' }
        ],
        priority: [
          { required: true, message: '请选择优先级', trigger: 'change' },
        ],
        endDate: [
          { required: true, message: '请选择截止日期', trigger: 'change' },
        ],
      },
      formData: {
        orderType: '',
        orderDesc: '',
        priority: '',
        endDate: '',
      },
      roamrules: {
        operType: [
          { required: true, message: '请选择操作类型', trigger: 'change' },
        ],
        character: [
          { required: false, message: '请选择转派角色', trigger: 'change' },
        ],
        roleId: [
          { required: false, message: '请选择转派用户', trigger: 'change' },
        ],
        operOpinions: [
          { required: true, message: '请输入操作意见', trigger: 'change' },
           { max: 200, message: '长度在 200个字符内', trigger: 'change' }
        ],
      },
      roamformInline: {
        operType: '',
        character: '',
        roleId: '',
        operOpinions: '',
      },
      tableData2: [],
      tableData: [],
      characteroptions: [],
      roleIdoptions: [],
      operationFlat: false,
      // 转派的控制
      reassignment: true,
      parentDynamic: []
    }
  },
  created () {
    // 资源续期
    this.ids = this.$route.query.resIds
    console.log(this.ids)
    if (this.ids !== undefined) {
      this.ids = JSON.parse(this.$route.query.resIds)
    }

    //  this.ids = [{
    //   resId:'77',
    //   parentId:"22062318301101",
    //   resourceName:'资源123321'
    // }]
    console.log(this.$route.query.resIds)
    // 根据参数判断是流转还是新增

    this.orderNo = this.$route.query.orderNo
    console.log(this.orderNo)
    if (this.orderNo !== undefined) {
      this.orderNoflat = true
      // 获取信息
      this.getselect()
      this.getdata()
      //  this.$nextTick(()=>{
      //  console.log(this.tableData)
      //  console.log(this.parentDynamic)
      // this.getDyna(this.parentDynamic, this.tableData[0].parentId)

      //  })
      // if (this.$store.state.loginUser.userFlag == '0') {
      if (this.$store.state.loginUser.userId == '1') {
        this.deleteflat = false
      }
    } else {
      // 新增
      this.operationFlat = true
      // 获取动态表格
      this.getDynamic()
    }
  },
  methods: {
    // 时间对话框的确定事件
    timeDialogSub () {
      this.$refs["timeRef"].validate((valid) => {
        if (valid) {
          console.log(this.tableDataCopy)
          this.addResource(this.tableDataCopy)
          this.timeForm.serviceLife = ''
          this.timeDialogVisible = false
        }
      })
    },
    // 解决表格选择不刷新页面的问题
    selectBlur () {
      this.tableData = JSON.parse(JSON.stringify(this.tableData))
    },
    // 获取动态表格的属性数据
    getDynamic () {
      this.$http({
        url: '/api/resources/catalog/listInfo',
        method: "get"
      }).then(res => {
        console.log(res.data.data)
        this.parentDynamic = res.data.data
        if (this.orderNo !== undefined) {
          console.warn(this.tableData)
          this.getDyna(this.parentDynamic, this.tableData[0].cataId)
          this.labels.forEach(item => {
            item.enumValue = typeof item.enumValue == 'object' ? item.enumValue : item.enumValue.split(',')
          })
        }
        // 续期的
        console.log(this.ids)
        if (this.ids !== undefined) {
          // 渲染表头
          this.getDyna(this.parentDynamic, this.ids[0].parent)
          this.labels.forEach(item => {
            item.enumValue = typeof item.enumValue == 'object' ? item.enumValue : item.enumValue.split(',')
          })
          // 添加续期的资源
          this.addResource(this.ids)
        }
      })
    },
    iaasApplyBtn () {
      this.iaasApplyDialog = true;
    },
    // 获取选择的值
    iassApplyDialogSub () {
      //选择的值
      let apply = this.$refs.IaasDialog.$refs.tableRef.selection
      this.$refs.IaasDialog.$refs.tableRef.clearSelection()
      this.iaasApplyDialog = false
      // 判断有没有同样的id数据,有的话去除
      this.tableDataCopy = apply.filter((v) =>
        this.tableData.every((val) => val.resId != v.resId)
      )
      // this.addResource(newArr)
      this.iaasApplyDialog = false
      this.timeDialogVisible = true
    },
    // 操作类型变化
    opachange (val) {
      console.log(val)
      // 如果是转派
      if (val == '2') {
        // 才填
        this.reassignment = false
        // 校验改变
        this.roamrules.character = [
          { required: true, message: '请选择转派角色', trigger: 'change' },
        ]
        this.roamrules.roleId = [
          { required: true, message: '请选择转派用户', trigger: 'change' },
        ]
      } else {
        this.reassignment = true
        // 清空数据
        this.roamformInline.character = ''
        this.roamformInline.roleId = ''
        // 清空转派校验的文字
        this.$refs.roamdialog.clearValidate(['character', 'roleId'])
        this.roamrules.character = [
          { required: false, message: '请选择转派角色', trigger: 'change' },
        ]
        this.roamrules.roleId = [
          { required: false, message: '请选择转派用户', trigger: 'change' },
        ]
      }
    },
    // 批量删除
    deleteon () {
      if (this.$refs.tableref.selection.length == '0') {
        this.$message({
          type: 'warning',
          message: '未选择行数据'
        })
        return
      }
      console.log(this.$refs.tableref.selection)
      // 进行删除操作
      this.$refs.tableref.selection.forEach(item => {
        this.tableData.forEach((item2, index) => {
          if (item == item2) {
            this.tableData.splice(index, 1)
          }
        })
      })

    },
    // 删除
    deleteone (index) {
      this.tableData.splice(index, 1)
    },
    // 循环添加判断是不是目录
    addcatalogue (arr) {
      arr.forEach(item => {
        item.iscatalogue = true
        if (item.children.length > 0) {
          this.addcatalogue(item.children)
        }
      })
    },
    // // 获取下拉的数据
    getselect () {
      this.$http({
        url: `/api/system/userRole/selectRoleList`,
        method: 'get',
      }).then(res => {
        this.characteroptions = res.data.data
      })
    },
    // 下拉变化
    characterchange (val) {
      this.roamformInline.roleId = ''
      if (val === '') {
        this.roleIdoptions = []
      } else {
        this.$http({
          url: `/api/system/userRole/selectRoleUserList/${val}`,
          method: 'get',
        }).then(res => {
          this.roleIdoptions = res.data.data
        })
      }
    },
    // 获取数据
    getdata () {
      this.$http({
        url: `/api/work/order/apply/${this.orderNo}`,
        method: 'get'
      }).then(res => {
        console.log(res)
        this.formData.orderType = res.data.data.orderType
        this.formData.orderDesc = res.data.data.orderDesc
        this.formData.priority = res.data.data.priority
        this.formData.endDate = res.data.data.endDate
        // 添加resid
        this.addResId(res.data.data.resourceApplyList)
        this.tableData = res.data.data.resourceApplyList
        console.log(this.tableData, '12122')
        this.tableData2 = res.data.data.workOrderTrackList
        this.roamflat = res.data.data.workStatus
        // 判读是不是创建人  控制添加修改的按钮显示隐藏
        if (this.$store.state.loginUser.userId == res.data.data.creator && res.data.data.workStatus == '2') {
          this.operationFlat = true
        }
        this.getDynamic()
        // 获取动态表格
      })
    },
    // 循环添加resid
    addResId (arr) {
      arr.forEach(item => {
        item.resId = item.resourceId
      })
    },
    getDyna (arr, id) {
      arr.forEach(item => {
        if (item.catalogId == id) {
          console.log(item)
          this.labels = item.resourceParamList
        }
        if (item.children) {
          this.getDyna(item.children, id)
        }
      })
    },
    addResource (apply) {
      console.log(apply)
      // 自动进入编辑状态
      this.tableEditable = true;
      // 处理数据  设置父亲id 和  动态表格项
      if (apply.length > 0) {
        this.getDyna(this.parentDynamic, apply[0].parentId)
      }
      // 
      console.log(this.parentDynamic)
      console.log(this.labels)
      this.labels.forEach(item => {
        item.enumValue = typeof item.enumValue == 'object' ? item.enumValue : item.enumValue.split(',')
        this.applyValue[item.applyKey] = {
          text: ""
        }
      })
      console.log(this.labels)
      apply.forEach(item => {
        this.tableData.push({
          parentId: item.parentId,
          resId: item.resId,
          resourceId: item.resId,
          resourceName: item.resourceName,
          serviceLife: this.timeForm.serviceLife,
          remark: '',
          applyValue: this.applyValue
        })
      })
    },
    saveTable () {
      // 校验备注是否在200字符内
      console.log(this.tableData[0].remark.length)
      try {
           this.tableData.forEach(item=>{
        if(item.remark.length>200){
          throw new Error('200字符')
        }
      })
      } catch (error) {
        if(error.message=='200字符'){
          this.$message.error('备注长度在200字符内')
          return
        }
      }
     
      // 判断是否都已填写除了备注
      this.tableEditable = false;
    },
    submit () {
      // 首先校验必填项是否都填
      // try {
      //   this.tableData.forEach(item => {
      //     for (const key in item) {
      //       if (key !== "remark" && item[key] === '') {
      //         throw new Error("1")
      //       }
      //       if (key == 'resourceNum' && item[key] <= 0) {
      //         throw new Error('2')
      //       }
      //       if (key == 'resourceName' && item[key] == '默认名称') {
      //         throw new Error('3')
      //       }
      //       item.platformName = 'IAAS'
      //     }
      //   })
      // } catch (error) {
      //   if (error.message == '1') {
      //     this.$message({
      //       type: 'warning',
      //       message: '申请资源列表除备注外必填'
      //     })
      //   }
      //   if (error.message == '2') {
      //     this.$message({
      //       type: 'warning',
      //       message: '资源数量应该大于0'
      //     })
      //   }
      //   if (error.message == '3') {
      //     this.$message({
      //       type: 'warning',
      //       message: '请选择资源名称，不应为默认名称'
      //     })
      //   }
      //   return
      // }
      // 判断是否是编辑状态
      if (this.tableEditable == true) {
        this.$message({
          type: 'warning',
          message: '数据还未保存'
        })
        return
      }
      // 提交申请
      //校验
      this.tableData.forEach(item => {
        item.platformName = 'IAAS'
        item.cataId = item.parentId
        delete item.parentId
      })
      this.formData.resourceApplyList = this.tableData
      if (this.orderNo == undefined) {
        this.$refs["formref"].validate((valid) => {
          if (valid) {
            // 新增的接口
            this.$http({
              url: '/api/work/order/apply/',
              method: 'post',
              data: this.formData
            }).then(res => {
              console.log(res, '2222')
              if (res.data.code == 200) {
                this.$message.success('工单提交成功!')
                this.$router.push('/resApplyWorkOrderManagement')
              } else {
                this.$message.error('工单提交失败!')
              }

            }).catch(err => {
              this.$message.error('工单提交失败!')
            })
          }
        });
      } else {
        // 流转
        let data = {
          operOpinions: this.roamformInline.operOpinions,
          operType: this.roamformInline.operType,
          orderNo: this.orderNo,
          // 用户id
          roleId: this.roamformInline.roleId,
          source: '1'
        }
        if (this.roamflat == '2') {
          this.$refs["roamdialog"].validate((valid) => {
            if (valid) {
              // 流转接口
              this.$http({
                url: '/api/work/track',
                method: 'post',
                data: data
              }).then(res => {
                // 修改的接口
                this.formData.orderNo = this.orderNo,
                  this.$http({
                    url: '/api/work/order/apply/update',
                    method: 'POST',
                    data: this.formData
                  }).then(res => {
                    console.log(res)
                    this.$router.push('/resApplyWorkOrderManagement')
                  })
              })
            }
          })
        } else {
          // 修改的接口
          this.formData.orderNo = this.orderNo,
            this.$http({
              url: '/api/work/order/apply/update',
              method: 'POST',
              data: this.formData
            }).then(res => {
              console.log(res)
              this.$router.push('/resApplyWorkOrderManagement')
            })
        }

      }
    }
  }
}
</script>

<style lang="scss" scoped>
.resource-apply {
  height: calc(100vh - 100px);
  background-color: #f8f8f8;
  padding: 5px 30px 10px;

  .main {
    height: 92%;
    background-color: white;
    overflow-y: auto;
    box-sizing: border-box;
    padding: 10px 20px;
    .title-info {
      position: relative;
      margin: 10px 0 15px;
      &::before {
        position: absolute;
        content: '';
        display: block;
        width: 3px;
        height: 90%;
        background-color: #55aaff;
        left: -8px;
        top: 6%;
      }
    }
  }
}
span.success {
  color: #67c23a;
}
</style>